<script setup lang="js">

import {ref, onMounted, computed, reactive} from "vue";
import {policy} from "@/api/preferenceArea.js";

const props = defineProps({
  value: {
    type: String,
  }
});

// TODO: 计算属性
const imageUrl = computed(() => {
  return props.value;
});
const imageName = computed(() => {
  if (props.value != null && props.value !== "") {
    return props.value.substr(props.value.lastIndexOf("/") + 1);
  } else {
    return null;
  }
});
const fileList = computed(() => {
  return [{
    name: imageName,
    url: imageUrl,
  }]
});
const showFileList = computed({
  get: function () {
    return props.value !== null && props.value !== '' && props.value !== undefined;
  },
  set: function (newValue) {
    // 这里应该定义如何处理设置新值的逻辑
  }
});

// TODO: 变量/数据
const dialogVisible = ref(false);
const dataObj = reactive({
  policy: '',
  signature: '',
  key: '',
  ossaccessKeyId: '',
  dir: '',
  host: '',
  // callback:'',
})
const useOss = ref(true);
const ossUploadUrl = ref('http://macro-oss.oss-cn-shenzhen.aliyuncs.com');
const minioUploadUrl = ref('http://localhost:8080/minio/upload');


// TODO: 方法
const emitInput = (value) => {
  this.$emit('input', value);
}
const handleRemove = (file, fileList) => {
  emitInput('');
}
const handlePreview = (file) => {
  dialogVisible.value = true;
}
const beforeUpload = (file) => {
  if (!useOss.value) {
    return true;//不使用oss不需要获取策略
  }
  return new Promise((resolve, reject) => {
    policy().then(res => {
      dataObj.policy = res.data.policy;
      dataObj.signature = res.data.signature;
      dataObj.ossaccessKeyId = res.data.accessKeyId;
      dataObj.key = res.data.dir + '/${filename}';
      dataObj.dir = res.data.dir;
      dataObj.host = res.data.host;
      resolve(true);
    }).catch(err => {
      console.log(err)
      reject(err);
    })
  })
}
const handleUploadSuccess = (res, file) => {
  showFileList.value = true;
  fileList.value.pop();
  let url = dataObj.host + '/' + dataObj.dir + file.name;
  if (!useOss.value) {
    url = res.data.url;  //不使用oss直接获取图片路径
  }
  fileList.value.push({name: file.name, url: url});
  emitInput(fileList.value[0].url);
}


</script>

<template>
  <el-upload
      :action="useOss ? ossUploadUrl:minioUploadUrl"
      :data="useOss?dataObj:null"
      list-type="picture"
      :multiple="false" :show-file-list="showFileList"
      v-model:file-list="fileList"
      :before-upload="beforeUpload"
      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :on-preview="handlePreview">
    <el-button type="primary">点击上传</el-button>
    <template #tip>
      <div class="el-upload__tip">
        只能上传jpg/png文件，且不超过10MB
      </div>
    </template>
  </el-upload>
  <el-dialog v-model="dialogVisible">
    <img width="100%" :src="fileList[0].url" alt="">
  </el-dialog>
</template>

<style scoped>

</style>